<template>
  <view class="teacher-status-container">
    <!-- 顶部筛选 -->
    <view class="filter-section">
      <view class="filter-row">
        <view class="filter-item">
          <text class="filter-label">星期:</text>
          <picker mode="selector" :range="weekdays" range-key="label" @change="onWeekdayChange">
            <view class="picker-text">{{ currentWeekdayLabel }}</view>
          </picker>
        </view>
        
        <view class="filter-item">
          <text class="filter-label">时间段:</text>
          <picker mode="selector" :range="timeSlots" range-key="label" @change="onTimeSlotChange" style="width: 150px;">
            <view class="picker-text">{{ currentTimeSlotLabel }}</view>
          </picker>
        </view>
      </view>
    </view>

    <!-- 统计信息 -->
    <view class="stats-section">
      <view :class="['stat-card', 'clickable', activeFilter === 'all' ? 'active' : '']" @click="showAllTeachers">
        <text class="stat-number">{{ totalTeachers }}</text>
        <text class="stat-label">教师总数</text>
      </view>
      <view :class="['stat-card', 'clickable', activeFilter === 'teaching' ? 'active' : '']" @click="prioritizeTeachingTeachers">
        <text class="stat-number">{{ teachingCount }}</text>
        <text class="stat-label">正在上课</text>
      </view>
      <view :class="['stat-card', 'clickable', activeFilter === 'free' ? 'active' : '']" @click="prioritizeFreeTeachers">
        <text class="stat-number">{{ freeCount }}</text>
        <text class="stat-label">空闲</text>
      </view>
    </view>

    <!-- 教师列表 -->
    <view class="teacher-list">
        <view class="teacher-row">
        <view 
          v-for="(teacher, index) in displayTeachers" 
          :key="index"
          :class="['teacher-card', teacher.isTeaching ? 'teaching' : 'free']"
        >
          <view class="teacher-info">
            <view class="teacher-avatar">{{ teacher.name.substring(0, 1) }}</view>
            <view class="teacher-details">
              <text class="teacher-name">{{ teacher.name }}</text>
              <text class="teacher-status" v-if="teacher.isTeaching">
                <text v-if="teacher.className">{{ teacher.className }}</text><br>
                <text v-if="teacher.className && teacher.location"> · </text>
                <text v-if="teacher.location">{{ teacher.location }}</text>
                <text v-if="!teacher.className && !teacher.location">上课中</text>
              </text>
              <text class="teacher-status free-status" v-else>空闲</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="teachers.length === 0 && !loading" class="empty-state">
      <text class="empty-text">暂无教师数据</text>
    </view>

    <!-- 加载提示 -->
    <view v-if="loading" class="loading-state">
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script>
import { getToken } from '@/utils/auth'
import config from '@/config'

export default {
  data() {
    return {
      loading: false,
      weekday: '1',
      timeSlot: '',
      weekdays: [
        { value: '1', label: '星期一' },
        { value: '2', label: '星期二' },
        { value: '3', label: '星期三' },
        { value: '4', label: '星期四' },
        { value: '5', label: '星期五' },
        { value: '6', label: '星期六' },
        { value: '7', label: '星期日' }
      ],
      timeSlots: [
        { label: '第1节: 8:30-9:15', value: '第1节: 8:30-9:15', startTime: '08:30', endTime: '09:15' },
        { label: '第2节: 9:25-10:10', value: '第2节: 9:25-10:10', startTime: '09:25', endTime: '10:10' },
        { label: '第3节: 10:30-11:15', value: '第3节: 10:30-11:15', startTime: '10:30', endTime: '11:15' },
        { label: '第4节: 11:25-12:10', value: '第4节: 11:25-12:10', startTime: '11:25', endTime: '12:10' },
        { label: '学习力: 14:00-14:45', value: '学习力: 14:00-14:45', startTime: '14:00', endTime: '14:45' },
        { label: '第6节: 14:55-15:40', value: '第6节: 14:55-15:40', startTime: '14:55', endTime: '15:40' },
        { label: '第7节: 16:00-16:45', value: '第7节: 16:00-16:45', startTime: '16:00', endTime: '16:45' },
        { label: '第8节: 16:55-17:40', value: '第8节: 16:55-17:40', startTime: '16:55', endTime: '17:40' },
          { label: '第9节: 19:00-19:45', value: '第9节: 19:00-19:45', startTime: '19:00', endTime: '19:45' },
        { label: '第10节: 19:55-20:40', value: '第10节: 19:55-20:40', startTime: '19:55', endTime: '20:40' }
      ],
      teachers: [], // 所有教师列表
      vocationalSchedules: [], // 班级课表
      labSchedules: [], // 实训室课表
      activeFilter: 'teaching', // 当前激活的过滤器: 'all' | 'teaching' | 'free'
      displayTeachers: [] // 用于渲染的教师列表（可以按交互排序）
    }
  },
  computed: {
    currentWeekdayLabel() {
      const item = this.weekdays.find(w => w.value === this.weekday)
      return item ? item.label : '星期一'
    },
    currentTimeSlotLabel() {
      const item = this.timeSlots.find(t => t.value === this.timeSlot)
      return item ? item.label : '请选择时间段'
    },
    // 排序后的教师列表：正在上课的排前面（基础排序）
    sortedTeachers() {
      return [...this.teachers].sort((a, b) => {
        if (a.isTeaching && !b.isTeaching) return -1
        if (!a.isTeaching && b.isTeaching) return 1
        return a.name.localeCompare(b.name)
      })
    },
    totalTeachers() {
      return this.teachers.length
    },
    teachingCount() {
      return this.teachers.filter(t => t.isTeaching).length
    },
    freeCount() {
      return this.teachers.filter(t => !t.isTeaching).length
    }
  },
  onLoad(options) {
    // 从URL参数获取星期和时间段
    if (options.weekday) {
      this.weekday = options.weekday
    } else {
      // 默认使用当前星期
      const now = new Date()
      let weekday = now.getDay()
      if (weekday === 0) weekday = 7
      this.weekday = weekday.toString()
    }
    
    if (options.timeSlot) {
      this.timeSlot = decodeURIComponent(options.timeSlot)
    } else {
      // 默认使用当前时间段
      this.timeSlot = this.getCurrentTimeSlot()
    }
    
    this.loadData()
  },
  methods: {
    // 获取当前时间对应的时间段
    getCurrentTimeSlot() {
      const now = new Date()
      const hours = now.getHours()
      const minutes = now.getMinutes()
      const currentTime = hours * 60 + minutes // 转换为分钟数
      
      // 时间段定义（分钟数）
      const timeRanges = [
        { slot: '第1节: 8:30-9:15', start: 8 * 60 + 30, end: 9 * 60 + 15 },
        { slot: '第2节: 9:25-10:10', start: 9 * 60 + 25, end: 10 * 60 + 10 },
        { slot: '第3节: 10:30-11:15', start: 10 * 60 + 30, end: 11 * 60 + 15 },
        { slot: '第4节: 11:25-12:10', start: 11 * 60 + 25, end: 12 * 60 + 10 },
        { slot: '学习力: 14:00-14:45', start: 14 * 60, end: 14 * 60 + 45 },
        { slot: '第6节: 14:55-15:40', start: 14 * 60 + 55, end: 15 * 60 + 40 },
        { slot: '第7节: 16:00-16:45', start: 16 * 60, end: 16 * 60 + 45 },
        { slot: '第8节: 16:55-17:40', start: 16 * 60 + 55, end: 17 * 60 + 40 }
      ]
      
      // 查找当前时间所在的时间段
      for (const range of timeRanges) {
        if (currentTime >= range.start && currentTime <= range.end) {
          return range.slot
        }
      }
      
      // 如果不在任何时间段内，返回最接近的下一个时间段
      for (const range of timeRanges) {
        if (currentTime < range.start) {
          return range.slot
        }
      }
      
      // 如果已经过了所有时间段，返回第一个时间段
      return this.timeSlots[0].value
    },
    
    onWeekdayChange(e) {
      this.weekday = this.weekdays[e.detail.value].value
      this.activeFilter = 'teaching'
      this.loadData()
    },
    onTimeSlotChange(e) {
      this.timeSlot = this.timeSlots[e.detail.value].value
      this.activeFilter = 'teaching'
      this.loadData()
    },
    async loadData() {
      this.loading = true
      try {
        await Promise.all([
          this.loadVocationalSchedules(),
          this.loadLabSchedules()
        ])
        this.extractTeachers()
      } catch (err) {
        console.error('加载数据失败:', err)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    // 加载班级课表
    async loadVocationalSchedules() {
      const token = getToken()
      if (!token) {
        console.error('Token 不存在，无法加载班级课表')
        return
      }
      
      try {
        // 第一步：先加载第一页获取总数
        const response = await uni.request({
          url: config.baseUrl + '/admin-api/ao/vocational-class-schedule/page',
          method: 'GET',
          header: {
            'Authorization': 'Bearer ' + token,
            'tenant-id': '1'
          },
          data: {
            pageNo: 1,
            pageSize: 100  // 改为 100，后端最大限制
          }
        })
        
        const [error, res] = response
        
        if (error) {
          console.error('加载班级课表网络错误:', error)
          return
        }
        
        if (!res || !res.data) {
          console.error('班级课表响应数据为空')
          return
        }
        
        if (res.data.code !== 0) {
          console.error('班级课表返回错误:', res.data.msg || res.data.message)
          return
        }
        
        const total = res.data.data?.total || 0
        const pageSize = 100
        const totalPages = Math.ceil(total / pageSize)
        
        // 第一页数据
        this.vocationalSchedules = res.data.data?.list || []
        
        // 如果有多页，继续加载剩余页面
        if (totalPages > 1) {
          const promises = []
          for (let page = 2; page <= totalPages; page++) {
            promises.push(
              uni.request({
                url: config.baseUrl + '/admin-api/ao/vocational-class-schedule/page',
                method: 'GET',
                header: {
                  'Authorization': 'Bearer ' + token,
                  'tenant-id': '1'
                },
                data: {
                  pageNo: page,
                  pageSize: pageSize
                }
              })
            )
          }
          
          const results = await Promise.all(promises)
          
          results.forEach(([error, res], index) => {
            if (!error && res && res.data && res.data.code === 0 && res.data.data) {
              const pageData = res.data.data.list || []
              this.vocationalSchedules.push(...pageData)
            }
          })
        }
        
      } catch (err) {
        console.error('加载班级课表失败:', err)
      }
    },
    // 加载实训室课表
    async loadLabSchedules() {
      const token = getToken()
      if (!token) {
        console.error('Token 不存在，无法加载实训室课表')
        return
      }
      
      try {
        // 第一步：先加载第一页获取总数
        const response = await uni.request({
          url: config.baseUrl + '/admin-api/ao/lab-schedule/page',
          method: 'GET',
          header: {
            'Authorization': 'Bearer ' + token,
            'tenant-id': '1'
          },
          data: {
            pageNo: 1,
            pageSize: 100  // 改为 100，后端最大限制
          }
        })
        
        const [error, res] = response
        
        if (error) {
          console.error('加载实训室课表网络错误:', error)
          return
        }
        
        if (!res || !res.data) {
          console.error('实训室课表响应数据为空')
          return
        }
        
        if (res.data.code !== 0) {
          console.error('实训室课表返回错误:', res.data.msg || res.data.message)
          return
        }
        
        const total = res.data.data?.total || 0
        const pageSize = 100
        const totalPages = Math.ceil(total / pageSize)
        
        // 第一页数据
        this.labSchedules = res.data.data?.list || []
        
        // 如果有多页，继续加载剩余页面
        if (totalPages > 1) {
          const promises = []
          for (let page = 2; page <= totalPages; page++) {
            promises.push(
              uni.request({
                url: config.baseUrl + '/admin-api/ao/lab-schedule/page',
                method: 'GET',
                header: {
                  'Authorization': 'Bearer ' + token,
                  'tenant-id': '1'
                },
                data: {
                  pageNo: page,
                  pageSize: pageSize
                }
              })
            )
          }
          
          const results = await Promise.all(promises)
          
          results.forEach(([error, res], index) => {
            if (!error && res && res.data && res.data.code === 0 && res.data.data) {
              const pageData = res.data.data.list || []
              this.labSchedules.push(...pageData)
            }
          })
        }
        
      } catch (err) {
        console.error('加载实训室课表失败:', err)
      }
    },
    // 提取所有教师并判断上课状态
    extractTeachers() {
      const teacherMap = new Map()
      
      // 星期字段映射
      const weekdayFieldMap = {
        '1': 'mondayCourse',
        '2': 'tuesdayCourse',
        '3': 'wednesdayCourse',
        '4': 'thursdayCourse',
        '5': 'fridayCourse',
        '6': 'saturdayCourse',
        '7': 'sundayCourse'
      }
      
      const courseField = weekdayFieldMap[this.weekday]
      
      // 解析时间段信息 - 提取节次数字
      const slotMatch = this.timeSlot.match(/第(\d+)节/)
      const slotNumber = slotMatch ? slotMatch[1] : null
      
      // 先收集所有教师名
      const allTeacherNames = new Set()
      
      // 从班级课表中收集所有教师名
      this.vocationalSchedules.forEach(schedule => {
        // 添加班主任
        if (schedule.classTeacher) {
          allTeacherNames.add(schedule.classTeacher)
        }
        
        // 从所有星期的课程中提取教师名
        Object.values(weekdayFieldMap).forEach(field => {
          const courseInfo = schedule[field] || ''
          if (courseInfo) {
            const lines = courseInfo.split(/[\r\n]+/).filter(line => line.trim())
            // 教师名通常在第2行（索引1）
            if (lines.length >= 2) {
              const teacherName = lines[1].trim()
              if (teacherName) {
                allTeacherNames.add(teacherName)
              }
            }
          }
        })
      })
      
      // 从实训室课表中收集教师名
      this.labSchedules.forEach(schedule => {
        Object.values(weekdayFieldMap).forEach(field => {
          const courseInfo = schedule[field] || ''
          if (courseInfo) {
            const lines = courseInfo.split(/[\r\n]+/).filter(line => line.trim())
            // 实训室格式: "年级 班级\r\n课程名 教师名"
            if (lines.length >= 2) {
              const courseAndTeacher = lines[1] || ''
              const parts = courseAndTeacher.split(/\s+/).filter(p => p.trim())
              if (parts.length >= 2) {
                const teacherName = parts.slice(1).join(' ')
                if (teacherName) {
                  allTeacherNames.add(teacherName)
                }
              }
            }
          }
        })
      })
      
      // 检查当前选择的星期和时间段，哪些教师在上课
      // 从班级课表检查
      this.vocationalSchedules.forEach(schedule => {
        // 检查classSection是否匹配当前时间段
        if (!this.isScheduleInTimeSlot(schedule, slotNumber)) {
          return
        }
        
        const courseInfo = schedule[courseField] || ''
        if (!courseInfo) return
        
        // 格式: "课程名\r\n教师名\r\n地点"
        const lines = courseInfo.split(/[\r\n]+/).filter(line => line.trim())
        
        if (lines.length >= 2) {
          const courseName = lines[0] || ''
          const teacherName = lines[1] || ''
          const locationInCourse = lines[2] || ''  // 课程信息中的第3行地点
          const className = schedule.className || ''
          const classroomField = schedule.classroom || ''  // 班级课表的教室字段
          
          // 优先使用课程信息中的地点，如果没有则使用班级固定教室
          const location = locationInCourse || classroomField
          
          if (teacherName) {
            teacherMap.set(teacherName, {
              name: teacherName,
              isTeaching: true,
              courseName: courseName,
              className: className,
              location: location || ''
            })
          }
        }
      })
      
      // 从实训室课表检查
      this.labSchedules.forEach(schedule => {
        // 检查classSection是否匹配当前时间段
        if (!this.isScheduleInTimeSlot(schedule, slotNumber)) {
          return
        }
        
        const courseInfo = schedule[courseField] || ''
        if (!courseInfo) return
        
        // 格式: "年级 班级\r\n课程名 教师名"
        const lines = courseInfo.split(/[\r\n]+/).filter(line => line.trim())
        
        if (lines.length >= 2) {
          const classLine = lines[0] || ''
          const courseAndTeacher = lines[1] || ''
          
          // 提取班级名（去掉年级）
          const gradeMatch = classLine.match(/^(高[一二三]|中[一二三])\s+(.+)$/)
          const className = gradeMatch ? gradeMatch[2] : classLine
          
          // 提取课程名和教师名
          const parts = courseAndTeacher.split(/\s+/).filter(p => p.trim())
          const courseName = parts[0] || ''
          const teacherName = parts.slice(1).join(' ') || ''
          
          // 实训室名称作为地点
          const labName = schedule.labName || schedule.lab_name || ''
          const location = labName || '实训室'
          
          if (teacherName && !teacherMap.has(teacherName)) {
            teacherMap.set(teacherName, {
              name: teacherName,
              isTeaching: true,
              courseName: courseName,
              className: className,
              location: location
            })
          }
        }
      })
      
      // 构建完整的教师列表
      this.teachers = Array.from(allTeacherNames).map(name => {
        if (teacherMap.has(name)) {
          return teacherMap.get(name)
        } else {
          return {
            name: name,
            isTeaching: false,
            courseName: '',
            className: '',
            location: ''
          }
        }
      })
      // 默认渲染列表使用基础排序（正在上课优先）
      this.applyFilter()
    },

    // 显示所有教师（按姓名排序）
    showAllTeachers() {
      this.activeFilter = 'all'
      this.applyFilter()
    },

    // 正在上课的教师置顶
    prioritizeTeachingTeachers() {
      this.activeFilter = 'teaching'
      this.applyFilter()
    },

    // 空闲教师置顶
    prioritizeFreeTeachers() {
      this.activeFilter = 'free'
      this.applyFilter()
    },

    // 应用当前过滤器/排序规则
    applyFilter() {
      if (!this.teachers || this.teachers.length === 0) {
        this.displayTeachers = []
        return
      }

      const base = [...this.teachers]

      switch (this.activeFilter) {
        case 'all':
          // 显示全部，按姓名排序
          this.displayTeachers = base.sort((a, b) => a.name.localeCompare(b.name))
          break
        
        case 'teaching':
          // 正在上课优先，然后按姓名排序
          this.displayTeachers = base.sort((a, b) => {
            if (a.isTeaching && !b.isTeaching) return -1
            if (!a.isTeaching && b.isTeaching) return 1
            return a.name.localeCompare(b.name)
          })
          break
        
        case 'free':
          // 空闲优先，然后按姓名排序
          this.displayTeachers = base.sort((a, b) => {
            if (!a.isTeaching && b.isTeaching) return -1
            if (a.isTeaching && !b.isTeaching) return 1
            return a.name.localeCompare(b.name)
          })
          break
        
        default:
          this.displayTeachers = this.sortedTeachers
      }
    },
    
    // 检查课表是否在指定时间段（参考 patrol/index.vue 的逻辑）
    isScheduleInTimeSlot(schedule, slotNumber) {
      if (!schedule.classSection || !slotNumber) return false
      
      const section = schedule.classSection.trim()
      
      // 清理换行符,统一格式
      const cleanSection = section.replace(/[\r\n]+/g, ' ').trim()
      
      // 提取节次数字(支持格式: "5"、"学习力"、"5 14:00-14:45"、"1\r\n08:30-09:15")
      const sectionMatch = cleanSection.match(/^(\d+)(?:\s|第|节|$)/) || cleanSection.match(/第(\d+)节/)
      
      if (sectionMatch) {
        const sectionNum = sectionMatch[1]
        return sectionNum === slotNumber
      }
      
      return false
    }
  }
}
</script>

<style lang="scss" scoped>
.teacher-status-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20px;
}

.filter-section {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
}

.filter-row {
  display: flex;
  gap: 10px;
}

.filter-item {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-label {
  font-size: 13px;
  color: #666;
  white-space: nowrap;
}

.picker-text {
  flex: 1;
  padding: 8px 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 13px;
  color: #333;
  background-color: #fff;
}

.stats-section {
  display: flex;
  gap: 10px;
  padding: 0 10px;
  margin-bottom: 10px;
}

.stat-card {
  flex: 1;
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.stat-card.clickable { 
  cursor: pointer; 
}

.stat-card.active {
  background-color: #3c96f3;
}

.stat-card.active .stat-number,
.stat-card.active .stat-label {
  color: #fff;
}

.stat-number {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #999;
}

.teacher-list {
  padding: 0 10px;
}

.teacher-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: space-between;
}

.teacher-card {
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  width: calc(50% - 5px);
  margin-bottom: 10px;
}

.teacher-card.teaching {
  border-left: 4px solid #3c96f3;
}

.teacher-card.free {
  border-left: 4px solid #ddd;
}

.teacher-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.teacher-avatar {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  background-color: #3c96f3;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 18px;
  font-weight: bold;
}

.teacher-card.free .teacher-avatar {
  background-color: #bdbdbd;
}

.teacher-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.teacher-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.teacher-status {
  font-size: 12px;
  color: #3c96f3;
  font-weight: 500;
}

.teacher-status.free-status {
  color: #999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 0;
  background-color: #fff;
  border-radius: 12px;
  margin: 10px;
}

.empty-text {
  font-size: 14px;
  color: #999;
}

.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.loading-text {
  font-size: 14px;
  color: #999;
}
</style>
